package com.siss.tenancy.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

public class Object2JsonString2ObjectUtil {

	
	public static <T> String Object2JsonString(T t){
		String s = null;
		ObjectMapper mapper = new ObjectMapper();
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		try {
			s = mapper.writeValueAsString(t);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("对象转json字符串失败");
			return null;
		}
		return s;
	}
	
	public static <T> String Object2JsonStringCustomDate(T t,String dateFormat){
		String s = null;
		ObjectMapper mapper = getCustomerDate(dateFormat);
		try {
			s = mapper.writeValueAsString(t);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("对象转json字符串失败");
			return null;
		}
		return s;
	}
	
	public static <T> List<T> jsonString2ObjectList(String jsonString, TypeReference t, String dateFormat) throws JsonParseException, JsonMappingException, IOException{
		
		List<T> list = null;
		//首先判断字符串是否是list形式的
		StringBuilder sb = null;
		if(!jsonString.startsWith("[")){//重构字符串
			sb = new StringBuilder("[");
			sb.append(jsonString).append("]");
		}else{
			sb = new StringBuilder(jsonString);
		}
		ObjectMapper mapper = getCustomerDate(dateFormat);
		try {
			list = mapper.readValue(sb.toString(), t);
			return list;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public static ObjectMapper getCustomerDate(String dateFormat){
		ObjectMapper mapper = new ObjectMapper();
		if(null != dateFormat){
			mapper.setDateFormat(new SimpleDateFormat(dateFormat));
		}
		return mapper;
	}
	
	
	/**  
	* 方法名: jsonString2Object  
	* 描述: TODO json转对象
	* 返回类型： T 
	* @param jsonString
	* @param new TypeReference(Class){}
	* @param dateFormat : yyyy-MM-dd HH:mm:ss
	* @return
	* @throws JsonParseException
	* @throws JsonMappingException
	* @throws IOException
	* 作者：liyipeng
	* 创建时间：2018年6月8日 下午5:20:30
	*/  
	public static <T> T jsonString2Object(String jsonString, TypeReference t, String dateFormat) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = getCustomerDate(dateFormat);
		T v = null;
		v = mapper.readValue(jsonString, t);
		return v;
	}
}
